//
//  MALHandler.m
//  iMAL
//
//  Created by Stefano Pigozzi on 1/30/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MALHandler.h"
#import "NetworkOperation.h"
#import "AnimeOperation.h"


@implementation MALHandler

@synthesize user;
@synthesize password;
@synthesize url;
@synthesize requestURL;
@synthesize absoluteRequestURL;

@synthesize app_delegate;
@synthesize progressSheet;

@synthesize progressCurrent;
@synthesize progressMaximum;
@synthesize progressMessage;

@synthesize scheduledOperations;

@synthesize loggedInState;

- (id) init
{
	self = [super init];
	if (self != nil) {
		
		self.url = @"http://myanimelist.net";
		self.loggedInState = kNotLoggedIn;
				
		self.scheduledOperations = [[NSOperationQueue new] autorelease];
		[self.scheduledOperations setMaxConcurrentOperationCount:4];
				
	}
	return self;
}

- (void) login
{
	[self post:@"/login.php" 
	  withData:[NSString stringWithFormat:@"username=%@&password=%@&cookie=true", 
				self.user, self.password]];
}

- (void) logout
{
	[self get:@"/panel.php?go=logout"];
}

- (void) post:(NSString *) resource withData:(NSString *) data
{
	NSURL * login_url = [NSURL URLWithString: [self.url stringByAppendingString:resource]];
	NSMutableURLRequest * url_request = [[NSMutableURLRequest alloc] initWithURL:login_url];
	
	[url_request setHTTPMethod:@"POST"];
	[url_request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[url_request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
	[url_request setHTTPBody:[data dataUsingEncoding:NSASCIIStringEncoding]];
	
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:url_request delegate:self];
	
	if (!connection) {
		NSLog(@"Failed to submit Post request");
	} else {
		NSLog(@"Post Request submitted");
		[responseData release];
		responseData = [[NSMutableData alloc] init];
		[connection release];
	}
	[url_request release];
}

- (void) getURL:(NSString *)absolute_url
{
	NSMutableURLRequest * url_request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: absolute_url]];
	
	[url_request setHTTPMethod:@"GET"];
	[url_request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[url_request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
	
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:url_request delegate:self];
	
	if (!connection) {
		NSLog(@"Failed to submit request");
	} else {
		[responseData release];
		responseData = [[NSMutableData alloc] init];
		[connection release];
	}
	[url_request release];
}

- (void) get:(NSString *) resource
{
	[self getURL:[self.url stringByAppendingString:resource]];
}

- (void) import
{
	[self get:[@"/malappinfo.php?u=" stringByAppendingString: self.user]];
}

- (void) deep_import
{	
	[self createFolders];
	[self post:@"/panel.php?go=export" withData:@"go=export&type=1&subexport=Export My List"];
}

-(void) createFolders
{
	NSLog(@"0");
	NSFileManager *fileManager = [NSFileManager defaultManager]; 
	NSString *folder = [NSString stringWithFormat:@"/Users/%@/Library/Application Support/iMAL/",NSUserName()];
	if ([fileManager fileExistsAtPath:folder] == NO) {
		NSLog(@"a");
		[fileManager createDirectoryAtPath:folder attributes:nil];
	}
	folder = [NSString stringWithFormat:@"/Users/%@/Library/Application Support/iMAL/images/",NSUserName()];
	if ([fileManager fileExistsAtPath:folder] == NO) {
		NSLog(@"b");
		[fileManager createDirectoryAtPath:folder attributes:nil];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	self.requestURL = [[[response URL] absoluteString] stringByMatching:self.url replace:RKReplaceAll withReferenceString:@""];
	self.absoluteRequestURL = [[response URL] absoluteString];
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[responseData appendData:data];
}

- (BOOL) isLoggedIn
{
	BOOL _yflag = NO;
	BOOL _zflag = NO;
	NSArray * cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:self.url]];
	for(NSHTTPCookie * cookie in cookies){
		if([[cookie name] isEqualToString:@"Y"])
			_yflag = YES;
		if([[cookie name] isEqualToString:@"Z"])
			_zflag = YES;
	}
	if(_yflag==YES && _zflag==YES){
		return YES;
	} else {
		return NO;
	}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
	
	//login
	if([self.requestURL isEqualToString: @"/login.php"])
	{
		if([self isLoggedIn] == YES){
			self.loggedInState = kLoggedIn;
		} else {
			self.loggedInState = kErrorLoggingIn;
		}
	}

	// response to deep xml request
	if([self.requestURL isMatchedByRegex:@"/panel.php.go=export"]){
		NSString *dlurl = [[[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding]
						   stringByMatching:@"(http://myanimelist.net/export/download.php.time=[0-9]*&t=anime&id=[0-9]*)" withReferenceFormat:@"$1"];
		[self getURL: dlurl];
	}
	// response is the deep xml import
	if([self.requestURL isMatchedByRegex:@"(/export/download.php.time=[0-9]*&t=anime&id=[0-9]*)"]){
		// saving export.xml.gz
		NSError * error;
		NSString * filename = [NSString stringWithFormat:@"/Users/%@/Library/Application Support/iMAL/export.xml.gz",NSUserName()];
		[responseData writeToFile:filename options:0 error: &error];
		// decompressing
		system([[NSString stringWithFormat:@"gunzip -f /Users/%@/Library/Application\\ Support/iMAL/export.xml.gz",NSUserName()]
				cStringUsingEncoding:NSASCIIStringEncoding]);
		// importing export.xml
		filename = [NSString stringWithFormat:@"/Users/%@/Library/Application Support/iMAL/export.xml",NSUserName()];
		NSData * xml_data = [[NSData alloc] initWithContentsOfFile:filename options:0 error:&error];
		// xml parser initialization
		NSXMLDocument * doc = [[NSXMLDocument alloc] initWithData:xml_data options:NSXMLDocumentTidyXML error:&error];
		NSXMLElement * root = [doc rootElement];		
		NSArray *animes = [root elementsForName:@"anime"];
		
		//setup data for progress bar
		[self setValue:[NSNumber numberWithInt:[animes count]*2] forKey:@"progressMaximum"];
		[self setValue:[NSNumber numberWithInt:0] forKey:@"progressCurrent"];
		[self setValue:@"Preparing for anime import" forKey:@"progressMessage"];
		
		[self.scheduledOperations cancelAllOperations];
		self.scheduledOperations = [NSOperationQueue new];
		[self.scheduledOperations setMaxConcurrentOperationCount:4];
		
		// transversing XML tree
		for(NSXMLElement * anime in animes){
			[self.scheduledOperations addOperation:[[AnimeOperation alloc] initWithXML:anime managedObjectContex:[app_delegate managedObjectContext] malHandler:self]];
		}
		[doc release];
		[xml_data release];
		return;
	}

}

-(void) hideProgressSheet
{
	[progressSheet orderOut:nil];
	[NSApp endSheet:progressSheet];
}

@end
